import cache from '@/libs/cache'
import apis from '@/apis/modules/base'
import { ACCESS_TOKEN, LOGIN_USER_INFO } from '../mutation-types'
import md5 from "md5"

export default {
  namespaced: true,
  state: {
    token: cache.get(ACCESS_TOKEN),
    userInfo: {},
    roles: ['admin', 'editor', 'visitor']

  },
  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
      if (token == null) {
        cache.remove(ACCESS_TOKEN)
        return false
      }
      cache.set(ACCESS_TOKEN, token, 2 * 60 * 60)
    },
    SET_USERINFO: (state, info) => {
      state.userInfo = info
      if (info == null) {
        cache.remove(LOGIN_USER_INFO)
        return false
      }
      cache.set(LOGIN_USER_INFO, info, 2 * 60 * 60)
    },

  },
  actions: {
    login({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        const ajaxDate = { ...userInfo }
        if (ajaxDate.password.length !== 32) {
          ajaxDate.password = md5(ajaxDate.password);
        }
        apis.login(userInfo).then(res => {
          commit('SET_USERINFO', res.data)
          commit('SET_TOKEN', res.data.token)
          resolve(res.data)
        }).catch(error => {
          reject(error)
        })
      })
    },
    logout({ commit, dispatch }) {
      return new Promise((resolve, reject) => {
        apis.logout().then(() => {
          commit('SET_TOKEN', null)
          commit('SET_USERINFO', null)
          // reset visited views and cached views
          // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
          dispatch('tagsView/delAllViews', null, { root: true })
          resolve(true)
        }).catch(error => {
          reject(error)
        })
      })
    },
    // dynamically modify permissions
    async changeRoles({ dispatch }, role) {
      // reset visited views and cached views
      dispatch('tagsView/delAllViews', null, { root: true })
    }

  }
}